import axios from 'axios'
import { Indicator, Toast } from 'mint-ui';
import config from '../config'
import ajaxintercept from './ajaxintercept'
import store from '../store/'
import plugins from '../plugins'

// TODO: 将缓存控制封装进server层中

let findData = (url, body = {}, methos = 'GET', key = '', deadline = 5) => {
  return new Promise((resolve, reject) => {
    
  })
}

let baseService1 = axios.create({
  baseURL: config.host + '/api',
  // baseURL: 'https://mb.quantsgeek.com/api',
  timeout: config.timeout,
  transformResponse: [function (data) {
    return JSON.parse(data)
  }]
})

baseService1.interceptors.request.use(config => {
    config.headers.Authorization = window.localStorage.getItem('token')
    store.state.loading = true
    return config
}, error => {
    store.state.loading = false
    Toast({
      message: '操作失败',
      duration: 1000
    })
    return Promise.reject(error)
})


baseService1.interceptors.response.use(response => {
    setTimeout(() => {
      store.state.loading = false
    }, 500)
    let res = JSON.parse(response.request.response)
    ajaxintercept.tokenValidate(res.code)
    if (res.code !== 200) {
      if (res.code === 6007 || res.code === 6006) {
        return Promise.reject()
      }
      if (res.msg === '请求参数错误') {
        return Promise.reject()
      }
      Toast({
        message: res.msg,
        duration: 1000
      })
      return Promise.reject()
    }
    return response
}, error => {
    store.state.loading = false
    if (!store.state.networkState) {
      plugins.networkErr()
      return Promise.reject(error)
    }
    if (error.toString().indexOf('timeout') > -1) {
      plugins.networkErr('网络连接超时，请检查您的网络')
      return Promise.reject('timeout')
    }
    Toast({
      message: '网络错误，请稍后再试',
      duration: 1000
    })
    return Promise.reject(error)
})

export default {
  baseService1
}